package com.zsj.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsj.config.Result;
import com.zsj.domain.User;
import com.zsj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 10652
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;


    @RequestMapping("login")
    public Result login(@RequestBody User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", user.getUsername());
        User dbUser = userService.getOne(queryWrapper);
        if (null == dbUser) {
            return Result.of(500, "没有该用户", false);
        }
        String pwd = DigestUtils.md5DigestAsHex((dbUser.getSalt() + user.getPassword()).getBytes());
        if (!Objects.equals(pwd, dbUser.getPassword())) {
            return Result.of(500, "密码错误", false);
        }
        String token = JWT.create()
                .setPayload("username", dbUser.getUsername())
                .setSigner(JWTSignerUtil.none())
                .sign();

        redisTemplate.delete("user_"+dbUser.getUsername());
        redisTemplate.opsForValue().set("user_"+dbUser.getUsername(), dbUser, 30, TimeUnit.MINUTES);
        redisTemplate.delete("token");
        redisTemplate.opsForValue().set("token", token, 30, TimeUnit.MINUTES);

        return Result.ok(token);
    }


    @RequestMapping("pwd")
    public void pwd() {
        String pwd = DigestUtils.md5DigestAsHex(("123" + "123456").getBytes());
        System.out.println(pwd);
    }
}
